/* eslint-disable */
import Browser from './browser'
import { cleanUp } from './functions'

const Print = {
  send: (params, printFrame) => {
    // 将iframe元素附加到文档正文
    if (params.type === 'pdf') {
      document.getElementsByTagName('body')[0].appendChild(printFrame)
    } else {
      previewAddDOM()
      document.getElementById('iframeDiv').appendChild(printFrame)
    }

    // 获取iframe文档
    const iframeElement = document.getElementById(params.frameId)

    // iframe载入完成
    iframeElement.onload = () => {
      if (params.type === 'pdf') {
        // 打印iframe的内容
        performPrint(iframeElement, params)
        return
      }

      // 获取iframe的文档流
      let printDocument = (iframeElement.contentWindow || iframeElement.contentDocument)
      if (printDocument.document) printDocument = printDocument.document

      // 将可打印的HTML插入iframe正文
      printDocument.body.innerHTML = params.htmlData

      // 添加自定义样式
      if (params.type !== 'pdf' && params.style !== null) {
        const style = document.createElement('style')
        style.innerHTML = params.style
        printDocument.head.appendChild(style)
      }

      document.getElementById('wePrintButton').addEventListener('click', function () {
        // 如果正在打印图像，请等待它们加载到iframe中
        const images = printDocument.getElementsByTagName('img')

        if (images.length > 0) {
          loadIframeImages(images).then(() => performPrint(iframeElement, params))
        } else {
          performPrint(iframeElement, params)
        }
      })

    }
  }
}

function previewAddDOM() {
  let wePrintPreviewStyle = `font-family: sans-serif;
    display: table;
    text-align: center;
    font-weight: 300;
    font-size: 30px;
    left: 0;
    top: 10%;
    position: fixed;
    z-index: 9990;
    width: 960px;
    height: 80%;
    background-color: #fff;
    left: 50%;
    overflow: auto;
    box-shadow: 1px 1px 50px rgba(0,0,0,.3);
    transform: translateX(-480px);`

  let previewStyle = '.wePrintPreviewClose{position:absolute;right:10px;top:10px}.wePrintPreviewClose:before{content:"\\00D7";font-family:"Helvetica Neue",sans-serif;font-weight:100;line-height:1px;padding-top:.5em;display:block;font-size:2em;text-indent:1px;overflow:hidden;height:1.25em;width:1.25em;text-align:center;cursor:pointer}.wePrintPreviewClose:before{content:"\\00D7";font-family:"Helvetica Neue",sans-serif;font-weight:100;line-height:1px;padding-top:.5em;display:block;font-size:2em;text-indent:1px;overflow:hidden;height:1.25em;width:1.25em;text-align:center;cursor:pointer}.wePrintButton{position:absolute;bottom:10px;padding: 5px 10px;left:50%;    transform: translateX(-50%);font-size: 16px;cursor: pointer;border-radius: 5px;background:#4F61CA;color:#fff;}'

  let previewModal = document.createElement('div')
  previewModal.setAttribute('style', wePrintPreviewStyle)
  previewModal.setAttribute('id', 'wePrint-Preview')

  let contentDiv = document.createElement('div')
  contentDiv.setAttribute('style', 'display:table-cell; vertical-align:middle;')

  const style = document.createElement('style')
  style.innerHTML = previewStyle
  contentDiv.appendChild(style)

  let iframeDiv = document.createElement('div')
  iframeDiv.setAttribute('id', 'iframeDiv')
  iframeDiv.setAttribute('style', 'width:100%;height:100%;padding:20px 20px 50px;overflow: auto;')
  contentDiv.appendChild(iframeDiv)

  let closeButton = document.createElement('div')
  closeButton.setAttribute('class', 'wePrintPreviewClose')
  closeButton.setAttribute('id', 'wePrintPreviewClose')
  contentDiv.appendChild(closeButton)

  let printButton = document.createElement('div')
  printButton.setAttribute('class', 'wePrintButton')
  printButton.setAttribute('id', 'wePrintButton')
  printButton.innerText = '打印'
  contentDiv.appendChild(printButton)

  previewModal.appendChild(contentDiv)

  document.getElementsByTagName('body')[0].appendChild(previewModal)

  document.getElementById('wePrintPreviewClose').addEventListener('click', function () {
    previewRemoveDOM()
  })
}
function previewRemoveDOM() {
  let printFrame = document.getElementById('wePrint-Preview')
  printFrame.parentNode.removeChild(printFrame)
}

function performPrint (iframeElement, params) {
  try {
    iframeElement.focus()
    // document.getElementById('printData').innerHTML = iframeElement.contentWindow.document.documentElement.innerHTML
    // previewAddDOM(iframeElement.contentWindow.document.documentElement.innerHTML)
    // Modal.show('123')


    // Edge或IE, 用execcommand执行打印命令
    if (Browser.isEdge() || Browser.isIE()) {
      try {
        iframeElement.contentWindow.document.execCommand('print', false, null)
      } catch (e) {
        iframeElement.contentWindow.print()
      }
    } else {
      // 其他浏览器直接打印
      iframeElement.contentWindow.print()
    }
  } catch (error) {
    params.onError(error)
  } finally {
    cleanUp(params)
  }
}

function loadIframeImages (images) {
  const promises = []

  for (let image of images) {
    promises.push(loadIframeImage(image))
  }

  return Promise.all(promises)
}

function loadIframeImage (image) {
  return new Promise(resolve => {
    const pollImage = () => {
      !image || typeof image.naturalWidth === 'undefined' || image.naturalWidth === 0 || !image.complete
        ? setTimeout(pollImage, 500)
        : resolve()
    }
    pollImage()
  })
}

export default Print
